<?php
/**
 * Created by PhpStorm.
 * User: xiaofeng
 * motto: 现在的努力是为了小时候吹过的牛逼！
 * Date: 2020/1/13
 * Time: 16:49
 */
namespace app\admin\business;
use app\common\model\mysql\AdminUser as AdminUserModel;
use think\Exception;

class AdminUser{

    public static function login($data){

        try{
            $adminUserObj = new AdminUserModel();
            $adminUser = self::getAdminUserByUsername($data['username']);

            if (empty($adminUser)){
                throw new Exception("不存在该用户");
            }

            if ($adminUser['password'] != md5($data['password'])){
                throw new Exception("密码错误");
            }

            // 需要记录信息到mysql
            $updateData = [
                "last_login_time"=>time(),
                "last_login_ip"=>request()->ip(),
                "update_time"=>time()
            ];

            $res = $adminUserObj->updateById($adminUser['id'],$updateData);

            if (empty($res)){
                throw new Exception("登录失败");
            }

        }catch (\Exception $e){
            throw new Exception("内部异常，登录失败");
        }
        session(config("admin.session_admin"),$adminUser);

        return true;
    }

    /**
     * 通过用户名获取用户数据
     * @param $username
     * @return array|bool|null|\think\Model
     */
    public static function getAdminUserByUsername($username){

        $adminUserObj = new AdminUserModel();
        $adminUser = $adminUserObj->getAdminUserByUsername($username);

        if (empty($adminUser) || $adminUser->status != config("status.mysql.table_normal")){
          return false;
        }
        $adminUser = $adminUser->toArray();
        return $adminUser;
    }

}